import * as monaco from 'monaco-editor'

import BwMonacoEditor from '@/utils/monacoEditor'
import { useComDesignStoreWithOut } from '@/store'
import { type BwCustomComStructModel } from '@bitwit/base-com-render'
import { ref, unref, toRaw, nextTick, watch, onBeforeUnmount } from 'vue'

const defaultStyle = `/**
* 温馨提示：在这里编写你的页面样式。
* 你可以点击面板上方的「使用帮助」了解。
*/
`

export function useNodeCss() {
  const bwMonacoEditor = new BwMonacoEditor()
  const designStore = useComDesignStoreWithOut()

  const cssEdit = ref()
  const curValue = ref<string>()
  const curNodeId = ref<string>('')
  const curEditor = ref<monaco.editor.IStandaloneCodeEditor | undefined>()

  const initCssLogic = (nodeInfo: Nullable<BwCustomComStructModel>) => {
    nextTick(() => {
      const value = nodeInfo?.css ?? defaultStyle
      if (value === unref(curValue)) {
        return
      }

      curValue.value = value
      curEditor.value = bwMonacoEditor.create({
        domElement: cssEdit.value,
        options: {
          value: value,
          wordWrap: 'on',
          language: 'css',
        },
        menus: undefined,
        snippets: undefined,
      })

      /** 监听编辑器内容变化 */
      const curEdit = unref(curEditor)
      if (curEdit) {
        curEdit.onDidChangeCursorPosition(function (e) {
          if (curEdit) {
            let readOnly = false
            if (e.position.lineNumber < 4) {
              readOnly = true
            }
            toRaw(curEdit).updateOptions({
              readOnly: readOnly,
            })
          }
        })

        curEdit.onDidChangeModelContent(() => {
          try {
            const curText = toRaw(curEdit).getValue()

            curValue.value = curText
            designStore.onChangeNodeEleCss(unref(curNodeId), curText)
          } catch (error) {
            console.warn('编辑器报错')
          }
        })
      }
    })
  }

  /** 编辑器关闭前保存内容 */
  onBeforeUnmount(() => {
    designStore.onChangeNodeEleCss(unref(curNodeId), unref(curValue) ?? '')
    bwMonacoEditor.dispose()
  })

  watch(
    () => designStore.selectNodeEle,
    (newVal) => {
      curNodeId.value = newVal?.nodeId ?? ''
      initCssLogic(newVal ?? null)
    },
    { deep: true, immediate: true }
  )
  return { cssEdit }
}
